/**
 * Created by Administrator on 2017/2/28.
 */
const http = require('http')
const url = require('url')
const querystring = require('querystring')

var request = {

  post: function (path, data, callback) {
    var contents = querystring.stringify(data)
    // http://localhost:3000/test
    var urlObject = url.parse(path)

    var option = {
      method: 'POST',
      hostname: urlObject.hostname,
      port: urlObject.port,
      path: urlObject.path,
      headers: {// 必选信息
        'Content-Type': 'application/x-www-form-urlencoded charset=UTF-8',
        'Content-Length': contents.length // 请求长度, 通过上面计算得到
      }
    }

    var Dispose = function (response) {
      var body = ''
      response.on('data', function (data) {
        body += data
      })
      response.on('end', function () {
        console.log(body)
        callback(body)
      })
    }

    var req = http.request(option, Dispose)

    req.write(contents)// 发送内容
    req.end()
  },

  get: function (path, data, callback) {
    var contents = querystring.stringify(data)
    // http://localhost:3000/test
    var urlObject = url.parse(path)

    var option = {
      method: 'GET',
      hostname: urlObject.hostname,
      port: urlObject.port,
      path: urlObject.path,
      headers: {// 必选信息
        'Content-Type': 'application/x-www-form-urlencoded charset=UTF-8',
        'Content-Length': contents.length // 请求长度, 通过上面计算得到
      }
    }

    var Dispose = function (response) {
      var body = ''
      response.on('data', function (data) {
        body += data
      })
      response.on('end', function () {
        console.log(body)
        callback(body)
      })
    }

    var req = http.request(option, Dispose)

    req.write(contents)// 发送内容
    req.end()
  }
}

module.exports = request
